#创建工具类
import pymysql
class DBtool:
#建立连接
    @staticmethod
    def __db_connect():
        coon = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                               password="iHRM_student_2022",database="ihrm", charset="utf8")
        return coon
#数据库查询
    @staticmethod
    def query_one(sql):
        coon=None
        cursor=None
        try:
            coon=DBtool.__db_connect()
            cursor=coon.cursor()
            cursor.execute(sql)
            ret=cursor.fetchone()
            return ret
        except Exception as err:
            print("查询一条出错了：",err)
        finally:
            cursor.close()
            coon.close()
    @staticmethod
    def query_many(sql,n):
        coon = None
        cursor = None
        try:
            coon = DBtool.__db_connect()
            cursor = coon.cursor()
            cursor.execute(sql)
            ret = cursor.fetchmany(n)
            return ret
        except Exception as err:
            print("查询多条出错了：", err)
        finally:
            cursor.close()
            coon.close()
    @staticmethod
    def query_all(sql):
        coon = None
        cursor = None
        try:
            coon = DBtool.__db_connect()
            cursor = coon.cursor()
            cursor.execute(sql)
            ret = cursor.fetchall()
            return ret
        except Exception as err:
            print("查询所有出错了：", err)
        finally:
            cursor.close()
            coon.close()
# 数据库增删改
    @staticmethod
    def db_idu(sql):
        coon = None
        cursor = None
        try:
            coon = DBtool.__db_connect()
            cursor = coon.cursor()
            cursor.execute(sql)
            coon.commit()
            if sql.find("insert")!=-1:
                print("增加操作成功")
            elif sql.find("delete")!=-1:
                print("删除操作成功")
            elif sql.find("update")!=-1:
                print("修改操作成功")
        except Exception as err:
            coon.rollback()
            print("操作不成功，原因是-->",err)
        finally:
            cursor.close()
            coon.close()
if __name__ == '__main__':
    # data1=DBtool.query_one(input("请用输入查询的sql语句"))
    # print("查询一条",data1)
    # # data2 = DBtool.query_many("select * from t_hero",3)
    # # print("查询多条", data2)
    # # data3 = DBtool.query_all("select * from t_hero")
    # # print("查询所有", data3)
    # DBtool.db_idu("insert into t_book  values(13,'西游记','2022-9-13','66','666','0')")
    DBtool.db_idu("delete from bs_user where mobile = '15000005555';")
    # DBtool.db_idu("update t_book set `read`= `read`+6 where id = 4")

